import { api } from './client';
import { Teacher, Course } from '../types';
import { mockTeacher, mockCourses } from './mockData';

// 辅助函数：尝试调用真实API，失败则使用mock
async function tryApiOrMock<T>(
  apiCall: () => Promise<T>,
  mockCall: () => T | Promise<T>
): Promise<T> {
  try {
    return await apiCall();
  } catch (e: any) {
    if (e.isMock || e.message === 'USE_MOCK_DATA') {
      return await mockCall();
    }
    throw e;
  }
}

export const loginTeacher = (username: string, password: string) => {
  return api<{ token: string; user: Teacher }>('/auth/login', {
    method: 'POST',
    body: JSON.stringify({ username, password, role: 'teacher' }),
  }).catch((error: any) => {
    if (error.isMock || error.message === 'USE_MOCK_DATA') {
      throw new Error('后端服务不可用，请检查后端是否正在运行');
    }
    throw error;
  });
};

export const getMe = () =>
  tryApiOrMock(
    () => api<Teacher>('/teachers/me'),
    () => Promise.resolve(mockTeacher)
  );

export const updateProfile = (data: Partial<Teacher>) =>
  tryApiOrMock(
    () => api<Teacher>('/teachers/me', {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
    () => {
      // Mock更新：更新mockTeacher对象
      Object.assign(mockTeacher, data);
      return Promise.resolve({ ...mockTeacher });
    }
  );

export const changePassword = (data: { oldPassword: string; newPassword: string }) =>
  tryApiOrMock(
    () => api<{ success: boolean }>('/auth/me/password', {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
    () => {
      return Promise.resolve({ success: true });
    }
  );

export type AppliedCourse = {
  id: string;
  name: string;
  time: string;
  credit: number;
  startWeek: number;
  endWeek: number;
  status: 'pending' | 'approved' | 'rejected';
  applyDate?: string;
};

// Mock数据存储
let mockAppliedCourses: AppliedCourse[] = [
  { id: '1', name: '数据结构与算法', time: '周一 14:00-16:00', credit: 3, startWeek: 1, endWeek: 16, status: 'approved', applyDate: '2023-10-05' },
  { id: '2', name: '人工智能导论', time: '周五 14:00-16:00', credit: 3, startWeek: 1, endWeek: 16, status: 'pending', applyDate: '2023-10-06' },
];

export const getAppliedCourses = () =>
  tryApiOrMock(
    () => api<AppliedCourse[]>('/teachers/me/applied-courses'),
    () => Promise.resolve([...mockAppliedCourses])
  );

export const applyCourse = (data: { 
  name: string; 
  time: string; 
  credit: number; 
  maxCapacity: number;
  startWeek: number;
  endWeek: number;
}) =>
  tryApiOrMock(
    () => api<{ id: string; name: string; status: string }>('/teachers/courses/apply', {
      method: 'POST',
      body: JSON.stringify(data),
    }),
    () => {
      // Mock申请：创建新的申请记录并添加到列表中
      const newCourse: AppliedCourse = {
        id: 'new-' + Date.now(),
        name: data.name,
        time: data.time,
        credit: data.credit,
        startWeek: data.startWeek,
        endWeek: data.endWeek,
        status: 'pending',
        applyDate: new Date().toISOString().split('T')[0],
      };
      // 添加到列表开头，这样新申请的会显示在最上面
      mockAppliedCourses = [newCourse, ...mockAppliedCourses];
      return Promise.resolve({
        id: newCourse.id,
        name: newCourse.name,
        status: newCourse.status,
      });
    }
  );

export const cancelApplication = (applicationId: string) =>
  tryApiOrMock(
    () => api<void>(`/teachers/courses/apply/${applicationId}`, {
      method: 'DELETE',
    }),
    () => {
      // Mock取消：从列表中移除该申请
      mockAppliedCourses = mockAppliedCourses.filter(c => c.id !== applicationId);
      return Promise.resolve();
    }
  );

export const getMyCourses = () =>
  tryApiOrMock(
    () => api<Course[]>('/teachers/me/courses'),
    () => {
      // Mock: 返回当前教师所教的课程（根据teacherName匹配）
      return Promise.resolve(
        mockCourses.filter(c => c.teacherName === mockTeacher.name)
      );
    }
  );

// 课程学生信息类型
export type CourseStudent = {
  id: string;
  studentNo: string;
  name: string;
  college: string;
  major: string;
  clazz: string;
};

export const cancelCourse = (courseId: string) =>
  tryApiOrMock(
    () => api<void>(`/teachers/courses/${courseId}`, { method: 'DELETE' }),
    () => {
      // Mock: 从mockCourses中移除该课程
      const index = mockCourses.findIndex(c => c.id === courseId);
      if (index !== -1) {
        mockCourses.splice(index, 1);
      }
      return Promise.resolve();
    }
  );

export const getCourseStudents = (courseId: string) =>
  tryApiOrMock(
    () => api<CourseStudent[]>(`/teachers/courses/${courseId}/students`),
    () => {
      // Mock: 根据课程返回选课学生列表
      const course = mockCourses.find(c => c.id === courseId);
      if (!course) {
        return Promise.resolve([]);
      }
      
      // 生成模拟学生数据
      const mockStudents: CourseStudent[] = Array.from(
        { length: course.enrolledCount || 0 },
        (_, i) => ({
          id: `stu-${courseId}-${i + 1}`,
          studentNo: `20210${String(i + 1).padStart(4, '0')}`,
          name: i === 0 ? '张明' : i === 1 ? '李华' : i === 2 ? '王芳' : `学生${i + 1}`,
          college: '计算机科学与技术学院',
          major: i % 3 === 0 ? '软件工程' : i % 3 === 1 ? '计算机科学与技术' : '人工智能',
          clazz: i % 3 === 0 ? '软件2101班' : i % 3 === 1 ? '计科2102班' : '智能2101班',
        })
      );
      
      return Promise.resolve(mockStudents);
    }
  );

